<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="父分组id" prop="parentId">
            <el-input v-model="queryParams.parentId" placeholder="请输入父分组id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="祖级列表" prop="ancestors">
            <el-input v-model="queryParams.ancestors" placeholder="请输入祖级列表" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="queryParams.groupName" placeholder="请输入分组名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否系统分组：1是，0否" prop="isSystem">
            <el-input v-model="queryParams.isSystem" placeholder="请输入是否系统分组：1是，0否" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input v-model="queryParams.orderNum" placeholder="请输入显示顺序" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['device:personGroup:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="loading"
        :data="personGroupList"
        row-key="groupId"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        ref="personGroupTableRef"
      >
        <el-table-column label="父分组id" align="center" prop="parentId" />
        <el-table-column label="祖级列表" align="center" prop="ancestors" />
        <el-table-column label="分组名称" align="center" prop="groupName" />
        <el-table-column label="分组类型：1学生；2教职工；3校外人员" align="center" prop="groupType" />
        <el-table-column label="是否系统分组：1是，0否" align="center" prop="isSystem" />
        <el-table-column label="显示顺序" align="center" prop="orderNum" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:personGroup:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['device:personGroup:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:personGroup:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改通行人员分组对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="personGroupFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父分组id" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="personGroupOptions"
            :props="{ value: 'groupId', label: 'groupName', children: 'children' }"
            value-key="groupId"
            placeholder="请选择父分组id"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="祖级列表" prop="ancestors">
          <el-input v-model="form.ancestors" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="是否系统分组：1是，0否" prop="isSystem">
          <el-input v-model="form.isSystem" placeholder="请输入是否系统分组：1是，0否" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PersonGroup" lang="ts">
import { listPersonGroup, getPersonGroup, delPersonGroup, addPersonGroup, updatePersonGroup } from "@/api/device/personGroup";
import { PersonGroupVO, PersonGroupQuery, PersonGroupForm } from '@/api/device/personGroup/types';

type PersonGroupOption = {
  groupId: number;
  groupName: string;
  children?: PersonGroupOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;


const personGroupList = ref<PersonGroupVO[]>([]);
const personGroupOptions = ref<PersonGroupOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const personGroupFormRef = ref<ElFormInstance>();
const personGroupTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const initFormData: PersonGroupForm = {
    groupId: undefined,
    parentId: undefined,
    ancestors: undefined,
    groupName: undefined,
    groupType: undefined,
    isSystem: undefined,
    orderNum: undefined,
    status: undefined,
    remark: undefined,
}

const data = reactive<PageData<PersonGroupForm, PersonGroupQuery>>({
  form: {...initFormData},
  queryParams: {
    parentId: undefined,
    ancestors: undefined,
    groupName: undefined,
    groupType: undefined,
    isSystem: undefined,
    orderNum: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    groupId: [
      { required: true, message: "分组id不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: true, message: "父分组id不能为空", trigger: "blur" }
    ],
    ancestors: [
      { required: true, message: "祖级列表不能为空", trigger: "blur" }
    ],
    groupName: [
      { required: true, message: "分组名称不能为空", trigger: "blur" }
    ],
    groupType: [
      { required: true, message: "分组类型：1学生；2教职工；3校外人员不能为空", trigger: "change" }
    ],
    isSystem: [
      { required: true, message: "是否系统分组：1是，0否不能为空", trigger: "blur" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询通行人员分组列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPersonGroup(queryParams.value);
  const data = proxy?.handleTree<PersonGroupVO>(res.data, "groupId", "parentId");
  if (data) {
    personGroupList.value = data;
    loading.value = false;
  }
}

/** 查询通行人员分组下拉树结构 */
const getTreeselect = async () => {
  const res = await listPersonGroup();
  personGroupOptions.value = [];
  const data: PersonGroupOption = { groupId: 0, groupName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<PersonGroupOption>(res.data, "groupId", "parentId");
  personGroupOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = {...initFormData}
  personGroupFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: PersonGroupVO) => {
  reset();
  getTreeselect();
  if (row != null && row.groupId) {
      form.value.parentId = row.groupId;
  } else {
      form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加通行人员分组";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(personGroupList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: PersonGroupVO[], status: boolean) => {
  data.forEach((item) => {
    personGroupTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: PersonGroupVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getPersonGroup(row.groupId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改通行人员分组";
}

/** 提交按钮 */
const submitForm = () => {
  personGroupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.groupId) {
        await updatePersonGroup(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addPersonGroup(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: PersonGroupVO) => {
  await proxy?.$modal.confirm('是否确认删除通行人员分组编号为"' + row.groupId + '"的数据项？');
  loading.value = true;
  await delPersonGroup(row.groupId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  getList();
});
</script>
